/**
 * 
 */
package info.niwota.webshot.web;

import info.niwota.commons.web.PageCursor;
import info.niwota.webapp.acl.CryptoHelper;
import info.niwota.webapp.web.PageContentProvider;
import info.niwota.webshot.Bookmarks;
import info.niwota.webshot.Debug;
import info.niwota.webshot.SDCard;

import java.io.File;

import android.content.Context;
import android.net.Uri;
import android.util.Log;

/**
 * 
 * Li, Qiang
 * 
 */
public class WebappPageContentProvider extends PageContentProvider {
	private static final String TAG = "WebappPageContentProvider";
	
	private static final int BOOKMARK_PAGE_SIZE = 10;

	@Override
	protected void showMainPage(PageCursor c, Uri uri, int group, String user,
			String path) throws Exception {
		handleAsset(c, "index.tpl", "text/html");
	}
	
	@Override
	protected boolean showContent(PageCursor c, Uri uri, int group,
			String user, String path) throws Exception {
		if (Debug.DEBUG) {
			Log.d(TAG, "showContent path: " + path + " uri: " + uri);
		}
		if (path.startsWith("/web/") && path.endsWith(".htmf")) {
			handleAsset(c, path.substring(1), "text/html");
			return true;
		}
		String label = null;
		int labelIdx = 0;
		if (path.startsWith("/webshot/")) {
			label = Label.MY_WEBSHOT;
			labelIdx = 1;
		} else if (path.startsWith("/bookmark/")) {
			label = Label.MY_BOOKMARK;
			labelIdx = 2;
		}
		
		if (label != null) {
			try {
				checkAccess(uri, group, user, label);
			} catch (Exception e) {
				c.type = PageCursor.Type.CONTENT;
				c.content = e.getLocalizedMessage();
				c.contentLength = c.content.length();
				return true;
			}
		}
		
		//proceed to generating content for the page
		switch (labelIdx) {
		case 1 : 
			if (path.endsWith("/index.html")) {
				handleAsset(c, "webshot.tpl", "text/html");
				return true;
			}
			if (path.endsWith("image")) {
				String img = uri.getQueryParameter("uri");
				handleImage(c, img, group, user);
				return true;
			}
			//load
			final String ws = loadWebshot(c, label, group, user);
			c.type = PageCursor.Type.CONTENT;
			c.contentType = "text/javascript";
			c.content = ws;
			c.contentLength = ws.length();
			break;
		case 2:
			final String bs = loadBookmark(uri, path);
			c.content = bs;
			c.contentLength = bs.length();
			c.contentType = "text/html";
			c.contentEncoding = "UTF-8";
			break;
		default:
		}
		return true;
	}
	
	private String loadBookmark(Uri uri, String path) {
		final int offset = toInt(uri.getQueryParameter("offset"), 0);
		//final int max = toInt(uri.getQueryParameter("max"), BOOKMARK_PAGE_SIZE);
		final int max = BOOKMARK_PAGE_SIZE;
		final Context ctx = getContext();
		int idx = path.lastIndexOf("/");
		final String data = Bookmarks.load(ctx,"", "/content/info.niwota.webshot/bookmark", path.substring(idx), offset, max, false);
		return data;
	}

	private int toInt(String s, int def) {
		try {
			return Integer.parseInt(s);
		} catch (Exception e) {
			// e.printStackTrace();
		}
		return def;
	}
	
	@Override
	protected int mapResource(String name) {
		//
		return super.mapResource(name);
	}
	
	private String loadWebshot(PageCursor c, String label, int group, String user) throws Exception {
		StringBuilder sb = new StringBuilder();
		
		final File root = SDCard.getWebshotDir();	
		
		if (root != null) {
			File[] uris = root.listFiles();
			int size = uris.length;
			//
			sb.append("(function () {\r\nimageCount = " + size + ";\r\n");
			sb.append("imageUris = new Array();\r\n");
			if (size > 0) {
				for (int i = 0; i < size; i++) {
					File f = uris[i];
					String p = f.getPath();
					//attach the label to the uri for perm check later when the uri is accessed
					String uri = f.toURI().toString();
					String hash = CryptoHelper.hash(p, label, group, user, true);
					String q = "?label="+label+"&hash="+hash;
					//
					sb.append("imageUris[" + i + "]=\"" + uri + q
							+ "\";\r\n");
				}
			}
			sb.append("})();\r\n");
			//cache - not modified
		}
		//
		return sb.toString();
	}
}
